/*
 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.io;


/**
 * 源为字符串的字符流。
 *
 * @author      Mark Reinhold
 * @since       JDK1.1
 */

public class StringReader extends Reader {

	// 内部的字符串 str
    private String str;
    // str的长度 length
    private int length;
    // str中读取的下一个字符的index
    private int next = 0;
    // 标记的index
    private int mark = 0;

    /**
     * 创建一个新的字符串读取器。
     *
     * @param s  String providing the character stream.
     */
    public StringReader(String s) {
        this.str = s;
        this.length = s.length();
    }

    /** 检查以确保流没有被关闭 close时str设置为null */
    private void ensureOpen() throws IOException {
        if (str == null)
            throw new IOException("Stream closed");
    }

    /**
     * 读取单个字符
     *
     * @return     The character read, or -1 if the end of the stream has been
     *             reached
     *
     * @exception  IOException  If an I/O error occurs
     */
    public int read() throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (next >= length)
                return -1;
            // 读取str上next位的char
            return str.charAt(next++);
        }
    }

    /**
     * 将字符读入数组的一部分。
     *
     * @param      cbuf  Destination buffer
     * @param      off   Offset at which to start writing characters
     * @param      len   Maximum number of characters to read
     *
     * @return     The number of characters read, or -1 if the end of the
     *             stream has been reached
     *
     * @exception  IOException  If an I/O error occurs
     */
    public int read(char cbuf[], int off, int len) throws IOException {
        synchronized (lock) {
            ensureOpen();
            if ((off < 0) || (off > cbuf.length) || (len < 0) ||
                ((off + len) > cbuf.length) || ((off + len) < 0)) {
                throw new IndexOutOfBoundsException();
            } else if (len == 0) {
                return 0;
            }
            if (next >= length)
                return -1;
            // 读取min(len,length-next)个char
            int n = Math.min(length - next, len);
            // str的字符复制到cbuf
            str.getChars(next, next + n, cbuf, off);
            next += n;
            return n;
        }
    }

    /**
     * 跳过流中的指定字符数。返回被跳过的字符数。
     *
     * <p>参数ns可能是负数，即使在这种情况下超类Reader的skip方法抛出了异常。
     * ns的负值会导致流向后跳跃。
     * 负的返回值表示向后滑动。
     * 不能向后跳过字符串的开头。
     *
     * <p>如果已读取或跳过整个字符串，则此方法无效，并始终返回0。
     *
     * @exception  IOException  If an I/O error occurs
     */
    public long skip(long ns) throws IOException {
        synchronized (lock) {
            ensureOpen();
            // 如果已读取或跳过整个字符串，返回0
            if (next >= length)
                return 0;
            // ns为正，跳跃长度为min(length-next,ns)
            // ns为负，跳跃长度为max(-next,n)
            long n = Math.min(length - next, ns);
            n = Math.max(-next, n);
            next += n;
            return n;
        }
    }

    /**
     * 告知该流是否已准备好读取。字符串读取器总是准备好被读取。
     *
     * @return True if the next read() is guaranteed not to block for input
     *
     * @exception  IOException  If the stream is closed
     */
    public boolean ready() throws IOException {
        synchronized (lock) {
        ensureOpen();
        return true;
        }
    }

    /**
     * 告知此流是否支持mark()操作，它确实支持。
     */
    public boolean markSupported() {
        return true;
    }

    /**
     * 标记流中的当前位置。
     * 后续调用reset()将把流重新定位到此处。
     *
     * @param  readAheadLimit  Limit on the number of characters that may be
     *                         read while still preserving the mark.  Because
     *                         the stream's input comes from a string, there
     *                         is no actual limit, so this argument must not
     *                         be negative, but is otherwise ignored.
     *
     * @exception  IllegalArgumentException  If {@code readAheadLimit < 0}
     * @exception  IOException  If an I/O error occurs
     */
    public void mark(int readAheadLimit) throws IOException {
        if (readAheadLimit < 0){
            throw new IllegalArgumentException("Read-ahead limit < 0");
        }
        synchronized (lock) {
            ensureOpen();
            mark = next;
        }
    }

    /**
     * 将流重置为最近的标记，如果从未被标记过，到开头。
     *
     * @exception  IOException  If an I/O error occurs
     */
    public void reset() throws IOException {
        synchronized (lock) {
            ensureOpen();
            // mark初始为0
            next = mark;
        }
    }

    /**
     * 关闭流并释放与之关联的任何系统资源。
     * 一旦流被关闭，进一步的read()、ready()、mark()、reset()或skip()调用将抛出一个IOException。
     * 关闭以前关闭的流没有任何效果。
     */
    public void close() {
        str = null;
    }
}
